"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/6/3 14:39
@Description :
"""
import datetime
import hashlib
import json

import jwt
from django.http import HttpResponse

from dept.models import Department
from role.models import Role
from utils.responsestatus import ResponseStatus


# 自定义序列化器
def customer_serializable(obj):
    if isinstance(obj, datetime.date):
        return obj.strftime('%Y-%m-%d')
    if isinstance(obj, Role):
        return {'id': obj.id, 'role_name': obj.role_name, 'role_en': obj.role_en, 'description': obj.description}
    if isinstance(obj, Department):
        return {'id': obj.id, 'dept_name': obj.dept_name, 'address': obj.address, 'create_time': obj.create_time}
    raise TypeError(f'Type {type(obj)} not serializable')


class CustomerUtils:

    @staticmethod
    def md5(data: str):
        return hashlib.md5(data.encode('utf-8')).hexdigest()

    @staticmethod
    def create_token(payload: dict, secret: str):
        return jwt.encode(payload, secret, algorithm='HS256')

    @staticmethod
    def verify_token(token: str, secret: str):
        return jwt.decode(token, secret, algorithms=['HS256'])

    @staticmethod
    def response_json(response_data):
        # TypeError: Object of type date is not JSON serializable
        return HttpResponse(json.dumps(response_data, default=customer_serializable).encode('utf-8'),
                            content_type='application/json;charset=UTF-8')

    @staticmethod
    def get_request_data(request):
        user_form = json.loads(request.body.decode('utf-8'))
        return user_form

    @staticmethod
    def create_qiniu_token():
        """
          生成七牛云上传token
        :return:
        """
        from qiniu import Auth
        # 需要填写你的 Access Key 和 Secret Key
        access_key = 'u48RMMuTxcgGpA5l9vmZiRypgOYFsUKmAyBVYeic'
        secret_key = 'V6Tvyfz-rN8eyFfxgj6KcVfPR44y7YCXPw1L-oLk'
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = 'python2511'
        # 上传后保存的文件名
        key = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        # 生成上传 Token，可以指定过期时间等
        # 上传策略示例
        # https://developer.qiniu.com/kodo/manual/1206/put-policy
        policy = {
            # 'callbackUrl':'https://requestb.in/1c7q2d31',
            # 'callbackBody':'filename=$(fname)&filesize=$(fsize)'
            # 'persistentOps':'imageView2/1/w/200/h/200'
        }
        # 3600为token过期时间，秒为单位。3600等于一小时
        token = q.upload_token(bucket_name, None, 3600, policy)

        return key, token
